package org.whuims.expertreader.excelreader;

import org.apache.poi.ss.usermodel.Sheet;
import org.whuims.expertreader.entity.*;

import javax.persistence.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Qikai Cheng
 * @date 五月 14 2018
 */
public class ExpertFileInput {
    private String filePath;
    private Map<String, String> topicIdMap = new HashMap<>();
    // Jpa Factory
    private EntityManagerFactory factory = Persistence.createEntityManagerFactory("demo");
    // Jpa Entity Manager
    private EntityManager manager = factory.createEntityManager();
    private Map<String, Author> authorIdMap = new HashMap<>();
    private Map<String, Topic> idTopicMap = new HashMap<>();

    public ExpertFileInput(String filePath) {
        this.filePath = filePath;
    }

    public void work() {
        PoiReader poiReader = new PoiReader(this.filePath);
        List<Sheet> sheetList = null;
        try {
            sheetList = poiReader.readExcel();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (Sheet sheet : sheetList) {
//            if (sheet.getSheetName().endsWith("学科举例")) {
//                List<String[]> stringsList = poiReader.readSheet(sheet);
//                updateTopics(stringsList);
//            }
            if (sheet.getSheetName().endsWith("论文")) {
                System.out.println(sheet.getSheetName());
                List<String[]> stringsList = poiReader.readSheet(sheet);
                processSheetData(stringsList);
            }
        }
        manager.close();
        factory.close();
    }

    private void processSheetData(List<String[]> stringsList) {
        System.out.println(stringsList.size());
        for (String[] strings : stringsList) {
            Author author = updateAuthors(strings);
            if (author == null) {
                continue;
            }
            processPaper(strings, author);
        }


    }

    private void processPaper(String[] strings, Author author) {
        String authorId = strings[0];
        String researchField = strings[1];
        String category = strings[2];
        String uniqueId = strings[3];
        String doi = strings[4];
        String title = strings[5];
        String keywords = strings[6];
        String summary = strings[7];
        String ccn = strings[8];
        Paper paper = findPaper(uniqueId);
        if (paper == null) {
            paper = new Paper();
            paper.getAuthorList().add(author);
            String[] ccnArray = ccn.split("[；;]");
            Topic topic = findTopic(ccnArray[0]);
            paper.setTopic(topic);
            Proceeding proceeding = new Proceeding();
            proceeding.setId(0L);
            paper.setProceeding(proceeding);
            paper.setTitle(title);
            paper.setKeywords(keywords);
            paper.setSummary(summary);
            paper.setUniqueId(uniqueId);
            paper.setAuid(paper.getAuid() + ";" + author.getId());
            paper.setAutext("unknown");
            paper.setDate("");
            paper.setInstext("");
            paper.setInstid("");
            paper.setYear(1900);

        } else {
            paper.getAuthorList().add(author);
        }
        EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        manager.persist(paper);
        transaction.commit();
    }

    private Paper findPaper(String uniqueId) {
        if (uniqueId == null || uniqueId.trim().equalsIgnoreCase("")) {
            return null;
        }
        Paper paper = null;
        uniqueId = uniqueId.trim();
        EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        Query query = manager.createQuery("select p from Paper p where p.uniqueId=?1");
        query.setParameter(1, uniqueId);
        List resultList = query.getResultList();
        if (resultList.size() > 0) {
            paper = (Paper) resultList.get(0);
        }
        transaction.commit();
        return paper;
    }

    private Author updateAuthors(String[] array) {
        String authorIdName = array[0];
        if (authorIdName == null || authorIdName.trim().equalsIgnoreCase("")) {
            return null;
        }
        Author author = findAuthor(authorIdName);
        if (author == null) {
            author = new Author();
            Institution institution = new Institution();
            institution.setId(0L);
            author.setName(authorIdName);
            author.setInstitution(institution);
            insertAuthor(author);
        }
        return author;
    }

    private void insertAuthor(Author author) {
        EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        manager.persist(author);
        transaction.commit();
        this.authorIdMap.put(author.getName(), author);
    }

    public Author findAuthor(String authorName) {
        Author author = null;
        if (this.authorIdMap.containsKey(authorName)) {
            return this.authorIdMap.get(authorName);
        }
        EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        Query query = manager.createQuery("select a from Author a where a.name=?1");
        query.setParameter(1, authorName);
        List resultList = query.getResultList();
        if (resultList.size() == 0) {

        } else {
            author = (Author) resultList.get(0);
            if (!this.authorIdMap.containsKey(authorName)) {
                this.authorIdMap.put(authorName, author);
            }
        }
        transaction.commit();
        return author;
    }

    public Topic findTopic(String label) {
        Topic topic = null;
        if (this.idTopicMap.containsKey(label)) {
            return this.idTopicMap.get(label);
        }
        EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        Query query = manager.createQuery("select t from Topic t where t.label=?1");
        query.setParameter(1, label);
        List resultList = query.getResultList();
        if (resultList.size() == 0) {
            topic = new Topic();
            topic.setId(0);
            topic.setLabel("unknown");
        } else {
            topic = (Topic) resultList.get(0);
            this.idTopicMap.put(label, topic);
        }
        transaction.commit();
        return topic;
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("请将excel文件地址作为参数输入");
        }
        String filePath = args[0].trim();
        ExpertFileInput input = new ExpertFileInput(filePath);
        input.work();
    }
}
